/*
 * GpsInternal.java
 *
 * Created on 12 de Maio de 2007, 12:49
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package net.onmotion.gps;

import javax.microedition.location.Criteria;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;

import net.onmotion.Location;
import net.onmotion.util.Log;

/**
 * 
 * @author sestevao
 */
public class GpsInternal extends Gps implements LocationListener {

  LocationProvider lp;

  javax.microedition.location.Location l;

  /** Creates a new instance of GpsInternal */
  public GpsInternal() {
    lp = null;
    l = null;
  }

  public net.onmotion.Location getLocation() {
    Location result = new Location();
    if (l != null && l.isValid()) {
      result.setLatitude(String.valueOf(l.getQualifiedCoordinates()
          .getLatitude()));
      result.setLongitude(String.valueOf(l.getQualifiedCoordinates()
          .getLongitude()));
      result.setAltitude(String.valueOf(l.getQualifiedCoordinates()
          .getAltitude()));
      result.valid = true;
    }
    return result;
  }

  public boolean isConnected() {
    return (lp != null);
  }

  public void start() {
    if (lp == null) {      
      Criteria cr = new Criteria();
      cr.setCostAllowed(true); // default value
      cr.setSpeedAndCourseRequired(true);
      cr.setHorizontalAccuracy(500);
      cr.setAltitudeRequired(true);
      try {        
        lp = LocationProvider.getInstance(cr);        
        if (lp != null) {          
          lp.setLocationListener(this, 10, -1, -1);
        } else {          
        }
      } catch (LocationException ex) {
        Log.log(ex);
      }
    }
  }

  public void stop() {
    if (lp != null) {
      lp.setLocationListener(null, -1, -1, -1);
      lp = null;
    }
  }

  public void locationUpdated(LocationProvider locationProvider,
      javax.microedition.location.Location location) {
    l = location;    
  }

  public void providerStateChanged(LocationProvider locationProvider, int i) {

  }

}
